﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace WriteFullDisk
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();

        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        
        
       /// <summary>
       /// 声明一个委托，委托是一个类，所以在使用的时候，要先创建一个实例
       /// </summary>
       /// <param name="s">被写入的文本</param>
        private delegate void writebox(string s);
       
        /// <summary>
        /// 将文本写入textbox的方法
        /// </summary>
        /// <param name="s">被写入的文本</param>
        private void box1(string s)
        {
            if (this.InvokeRequired)
            {
                //这里没弄懂，但是能凑合执行了
                writebox dd = new writebox(box1);
                this.Invoke(dd, new object[] {s });                
            }
            else
            {
                //希望委托执行的代码
                this.textBox2.Text =  "剩余空间："+s+"MB"+"\r\n";
                this.progressBar1.Value = this.progressBar1.Maximum- Convert.ToInt32(s);
            }            
        }
        /// <summary>
        /// 新线程执行的方法
        /// </summary>
        private void thbox()
        {
            //创建一个委托的实例
            writebox ww = new writebox(box1);           
            long freespace = GetHardDiskSpace(this.textBox1.Text);           
            string tt =freespace.ToString(); 
            ww(tt);
        }
       
        private void note()
        {
            //关于委托的简易说明
            //            2.1.委托 既是方法：

            //               声明委托的方式如下：在修饰符后加上 delegate ['dɛlɪɡət]关键字



            //public delegate void Del(string message);

            //        从格式上看，它与方法的声明极为相似，就是多了个 delegate关键字而已

            //              表示声明了一类，修饰符为public、一个string类型形参的、没有返回值的方法

            //     2.2. 但 委托 不是普通的方法，因为 它也是类，

            //            所以委托只能声明，而不能定义，如不能这样写：


            //private delegate void Doing(string name){
            //      System.Windows.MessageBox.Show();
            //}

            //　　2.3. 实例化委托，调用委托


            ////声明一个void, 形参是string的委托
            //public delegate void Del(string name);

            //    //定义个个cut方法
            //    public void cut(string name)
            //    {
            //        System.Windows.MessageBox.Show("fuck " + name);
            //    }
            //    //实例化委托，传的参数是一个方法的名字，这里是cut
            //    Del a = new Del(cut);
            //    a("CCC");//调用委托，相当于调用cut("CCC");
        }
        /// <summary>
        /// 选择要写入的磁盘，选中文件夹也可以，会自动截取第一个字母作为磁盘。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {

            dialog.Description = "请选择Txt所在文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "文件夹路径不能为空", "提示");

                }
                else
                {
                    this.textBox1.Text = dialog.SelectedPath;
                }
            }
            this.progressBar1.Maximum = (int)GetHardDiskTotalSpace(this.textBox1.Text);
        }
        private void WriteTxt()
        {

            string disk = this.textBox1.Text.Substring(0, 1);
            Random r = new Random();
            int num = r.Next(10000, 99999);//随机生成一个5位整数,再加上毫秒数，防止文件重名
            string filename = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000).ToString() + num.ToString();
            DateTime currentTime = System.DateTime.Now;
            string folder = currentTime.ToString("yyyyMMddHHmm");
            //string strFilePath =disk+ @":\empty.txt";
            string strFilePath = disk + ":\\" + folder + "\\" + filename;
            //创建文件夹
            if (!Directory.Exists(disk + ":\\" + folder))
            {
                Directory.CreateDirectory(disk + ":\\" + folder);
            }
            try{
                //创建用指定大小的空字符填充的文本文件           
                FileStream fs = new FileStream(strFilePath, FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(fs); // 创建写入流
                string txt = "";
                for (int i = 0; i < 1024; i++)
                {
                    txt += r.Next(10, 99).ToString();
                }
                for (int i = 0; i < 4000; i++)
                {
                    sw.WriteLine(txt); // 写入Hello World

                }
                sw.Close(); //关闭文件
                fs.Close();

            }
            catch (Exception e)
            {
                Thread.Sleep(50);
                
            }
            }
        //开启定时器，定时创建新线程
        private void buttonwrite_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            
        }
        private void DoWrite()
        {
           
           
        }
        /// <summary>
        /// 停止定时器，停止创建新线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonstop_Click(object sender, EventArgs e)
        {
          
            timer1.Enabled = false;

        }
        //磁盘剩余容量，单位ＭＢ
        public static long GetHardDiskSpace(string str_HardDiskName)
        {
            long totalSize = 0;            
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();            
            foreach (System.IO.DriveInfo drive in drives)
            {              
                if (drive.Name.Substring(0,1).ToUpper() == str_HardDiskName.Substring(0,1).ToUpper())
                {
                    totalSize = drive.TotalFreeSpace / (1024 * 1024);
                }
            }             
            return (totalSize);
        }
        //查询磁盘总容量，单位ＭＢ
        public static long GetHardDiskTotalSpace(string str_HardDiskName)
        {
            long totalSize = 0;
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
            foreach (System.IO.DriveInfo drive in drives)
            {
                if (drive.Name.Substring(0, 1).ToUpper() == str_HardDiskName.Substring(0, 1).ToUpper())
                {
                    totalSize = drive.TotalSize/ (1024 * 1024);
                }
            }
            return (totalSize);
        }

        private void buttonview_Click(object sender, EventArgs e)
        {
           

            Thread fThread = new Thread(new ThreadStart(thbox));
            fThread.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DateTime currentTime = System.DateTime.Now;
            string s = currentTime.ToString("yyyyMMddHHmm"); ;
            MessageBox.Show(s);
        }
        /// <summary>
        /// 定时创建新线程，写入一个文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            long space = GetHardDiskSpace(this.textBox1.Text.Substring(0, 1));
            if (space > 10)
            {
                Thread write = new Thread(WriteTxt);
                write.Start();
                Thread fThread = new Thread(new ThreadStart(thbox));
                fThread.Start();
            }
            else
            {
                MessageBox.Show("space is full");
                timer1.Enabled = false;
                timer1.Stop();
                Application.ExitThread();
            }
        }
        //调整新线程的触发时间，用以调整磁盘占用率
        private void button3_Click(object sender, EventArgs e)
        {
            this.timer1.Interval -= 10;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            this.timer1.Interval += 10;
        }
    }
}
